package org.devops

// 封装HTTP
def HttpReq(reqType, reqUrl, reqBody) {
    def sonarServer = "http://192.168.57.15:9000/api"
    withCredentials([string(credentialsId: 'gitlab-token', variable: 'gitlabToken')]) {
        result = httpRequest authentication: 'sonar-admin-test',
                httpMode: reqType,
                contentType: "APPLICATION_JSON",
                consoleLogResponseBody: true,
                ignoreSslErrors: true,
                requestBody: reqBody,
                url: "${sonarServer}/${reqUrl}"
    }
    return result
}

// 获取Sonar质量阈状态
def GetProjectStatus(projectName) {
    // http://192.168.57.15:9000/api/project_branches/list?project=demo-maven-service_PUSH
    apiUrl = "project_branches/list?project=${projectName}"

    response = HttpReq("GET", apiUrl, '')

    respJson = readJSON text: """${response.content}"""
    result = respJson["branches"][0]["status"]["qualityGateStatus"]

    return result
}

// 搜索项目
def SearchProject(projectName) {
    apiUrl = "projects/search?projects=${projectName}"

    response = HttpReq("GET", apiUrl, '')

    respJson = readJSON text: """${response.content}"""
    result = respJson["paging"]["total"]

    if (result.toString() == "0") {
        return "false"
    } else {
        return "true"
    }
}

// 创建Sonar项目
def CreateProject(projectName) {
    apiUrl = "projects/create?name=${projectName}&project=${projectName}"
    response = HttpReq("POST", apiUrl, '')

    println(response)
}

// 配置项目质量规则
def ConfigQualityProfiles(projectName, lang, qualityProfile) {
    apiUrl = "qualityprofiles/add_project?language=${lang}&project=${projectName}&qualityProfile=${qualityProfile}"
    response = HttpReq("POST", apiUrl, '')
    println(response)
}

// 获取质量阈ID
def GetQualityGateId(gateName) {
    apiUrl = "qualitygates/show?name=${gateName}"
    response = HttpReq("POST", apiUrl, '')
    respJson = readJSON text: """${response.content}"""
    id = respJson["id"] ?: 0
    return id
}

// 配置项目质量阈
def ConfigQualityGates(projectName, gateName) {
    gateId = GetQualityGateId(gateName)

    apiUrl = "qualitygates/select?gateId=${gateId}&projectKey=${projectName}"
    response = HttpReq("POST", apiUrl, '')
    println(response)
}